package com.lighting.smssystem.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.httpclient.HTTPException;
import com.lighting.smssystem.aspect.RequireRole;
import com.lighting.smssystem.constrants.UserRole;
import com.lighting.smssystem.model.Template;
import com.lighting.smssystem.model.User;
import com.lighting.smssystem.model.vo.AdminLogin;
import com.lighting.smssystem.model.vo.RestorePassword;
import com.lighting.smssystem.model.vo.UserLoginVo;
import com.lighting.smssystem.service.ISmsService;
import com.lighting.smssystem.service.IUserService;
import com.lighting.smssystem.service.impl.MiaodiyunSmsServiceImpl;
import com.lighting.smssystem.utils.BaseResponse;
import com.lighting.smssystem.utils.JWTUtils;
import com.lighting.smssystem.utils.ResponseUtil;
import com.lighting.smssystem.utils.SnowflakeIdWorker;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author LeeMaster
 *
 * 注册 登陆 找回密码 生成验证码 检查手机号是否可用
 *
 * 注册流程 验证手机号是否重复和可用 ，发送短信验证码，
 */
@RestController
@RequestMapping("/cred")
@Api(
        value = "基础功能模块",
        protocols = "http",
        description = "登陆注册"
)
@Slf4j
public class CredentialsController {

    @Resource
    ISmsService smsService;

    @Resource
    IUserService userService;

    @Autowired
    MiaodiyunSmsServiceImpl miaodiyunSmsService;

    @ApiOperation(
            value = "创建用户",
            httpMethod = "POST",
            notes = "前端生成验证码 调用后端接口发送验证码，前端验证验证码成功直接调用接口创建用户,创建成功返回200",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )

    )
    @PostMapping("/register")
    public BaseResponse registerUser(
            @ApiParam @RequestBody User user
            ){
        log.info("注册用户{}", user.toString());
        return ResponseUtil.success(userService.createUser(user));
    }

    @ApiOperation(
            value = "检查手机号是否可用 用于修改和注册使用",
            httpMethod = "GET",
            notes = "如果可用返回code 200 不可用 code 400",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )

    )
    @GetMapping("/phone")
    public BaseResponse verifyPhone(
            @ApiParam @RequestParam("phone")String phone
    ){
        log.info("验证手机号{}", phone);
        if (userService.verifyPhone(phone)) {
            return ResponseUtil.success();
        }
        return ResponseUtil.failed(400, "手机号已存在");
    }

    @ApiOperation(
            value = "发送短信验证码 登录使用",
            httpMethod = "GET",
            notes = "如果可用返回code 200 不可用 code 400",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )

    )
    @GetMapping("/verifyCode")
    public BaseResponse sendCode(
            @ApiParam @RequestParam("phone")String phone,
            @ApiParam @RequestParam("code") String code
    ) throws HTTPException, IOException {
        log.info("手机号{}, 验证码{}", phone, code);
        if (userService.verifyPhone(phone)) {
            log.error("用户不存在");
            return ResponseUtil.failed(400, "不存在该用户");
        }
        // 166465 验证码模版ID
        Template template = new Template();
        template.setTemplateExtId(166465);
        Map<String, String> params = new HashMap<>();
        params.put("1", code);
        ArrayList<String> phones = new ArrayList<>();
        phones.add(phone);
        // 发送短信
        miaodiyunSmsService.sendMsg(template, phones, params);
//        smsService.sendSingleSms(template, params, phone);
        return ResponseUtil.success();
    }

    @ApiOperation(
            value = "发送短信验证码 注册使用",
            httpMethod = "GET",
            notes = "如果可用返回code 200 不可用 code 400",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )

    )
    @GetMapping("/registerCode")
    public BaseResponse sendCodeReg(
            @ApiParam @RequestParam("phone")String phone,
            @ApiParam @RequestParam("code") String code
    ) throws HTTPException, IOException {
        log.info("注册或者修改手机号{}, 验证码{}", phone, code);
        if (!userService.verifyPhone(phone)) {
            log.error("该用户已存在");
            return ResponseUtil.failed(400, "该用户已存在");
        }
        // 166466 验证码模版ID
        Template template = new Template();
        template.setTemplateExtId(166466);
        Map<String, String> params = new HashMap<>();
        params.put("1", code);
        ArrayList<String> phones = new ArrayList<>();
        phones.add(phone);
        // 发送短信
        miaodiyunSmsService.sendMsg(template, phones, params);
        return ResponseUtil.success();
    }

    @GetMapping("/infoUpdate")
    public BaseResponse sendInfoUpdate(
            @ApiParam @RequestParam("phone") String phone
    ) {
        log.info("发送信息更新提示，手机号：{}", phone);
        if (userService.verifyPhone(phone)) {
            log.error("用户不存在");
            return ResponseUtil.failed(400, "不存在该用户");
        }
        // 166470 验证码模版ID
        Template template = new Template();
        template.setTemplateExtId(166470);
        ArrayList<String> phones = new ArrayList<>();
        phones.add(phone);
        // 发送短信
        miaodiyunSmsService.sendMsg(template, phones, new HashMap<>());
//        smsService.sendSingleSms(template, params, phone);
        return ResponseUtil.success();
    }

    @ApiOperation(
            value = "重置密码",
            httpMethod = "POST",
            notes = "更换成功返回 200 Code 失败 返回400 ",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )

    )
    @GetMapping("/pass")
    @RequireRole(role = UserRole.ADMIN)
    public BaseResponse restorePassword(
            @ApiParam @RequestParam("id") Long userId
            ){
        log.info("重置用户密码");
        return ResponseUtil.success(userService.resetUserPwd(userId));
    }

    @ApiOperation(
            value = "登陆",
            httpMethod = "POST",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )

    )
    @ApiResponse(code = 200,message = "",response = UserLoginVo.class)
    @PostMapping("/login")
    public BaseResponse loginUser(
            @ApiParam @RequestBody Map<String, String> body
            ){
        log.info("手机号{}, 验证码{}", body.get("phone"), body.get("code"));
        User user = userService.queryByPhone(body.get("phone"));
        if (user == null) {
            return ResponseUtil.failed(400, "不存在该用户");
        }
        if (!user.getUserPassword().equals(body.get("code"))) {
            return ResponseUtil.failed(400, "密码错误");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("id", user.getUserId().toString());
        data.put("token", JWTUtils.createJwt(user));
        log.info("返回的用户信心{}", data.toString());
        return ResponseUtil.success(data);
    }

    @ApiOperation(
            value = "登陆",
            httpMethod = "GET",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )

    )
    @ApiResponse(code = 200,message = "",response = UserLoginVo.class)
    @PostMapping("/loginAdmin")
    public BaseResponse loginAdmin(
            @ApiParam @RequestBody AdminLogin login
            ){
        log.info("管理员登录{}", login.toString());
        User user = userService.queryByPhone(login.getPhone());
        if (user == null) {
            return ResponseUtil.failed(400, "用户不存在");
        }
        if (user.getUserRole() != UserRole.ADMIN) {
            return ResponseUtil.failed(400, "用户不是管理员，请联系管理员开通权限");
        }
        JSONObject data = new JSONObject();
        data.put("id", user.getUserId().toString());
        data.put("token", JWTUtils.createJwt(user));
        return ResponseUtil.success(data);
    }

    @ApiOperation(
            value = "获取用户信息",
            httpMethod = "GET",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )
    )
    @GetMapping("/info")
    public BaseResponse userInfo(
            @ApiParam @RequestParam("id") Long id,
            @ApiParam @RequestParam("token") String token
    ) {
        log.info("用户id{}， 请求token{}", id, token);
        User user = userService.queryById(id);
        if (user == null) {
            return ResponseUtil.failed(400, "用户不存在");
        }
        return ResponseUtil.success(user);
    }

    @ApiOperation(
            value = "登出",
            httpMethod = "POST",
            authorizations = @Authorization(
                    "ADMIN 用户"
            )
    )
    @GetMapping("/logout")
    public BaseResponse logout(
            @ApiParam @RequestParam("id") Long id
    ) {
        log.info("user {} logout", id);
        BaseResponse<JSONObject> res = new BaseResponse();
        res.setCode(200);
        res.setMsg("success");
        return res;
    }
}
